package com.mxdx.edu.controller;


import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mxdx.edu.common.VnHttpForwardHanlder;
import com.mxdx.edu.model.StudentScore;
import com.mxdx.edu.service.*;
import com.mxdx.edu.util.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.mxdx.edu.common.ApiResult;
import com.mxdx.edu.common.CommonUtils;
import com.mxdx.edu.common.log.AppLogger;
import com.mxdx.edu.enums.ErrorEnums;
import com.mxdx.edu.util.ServletUtil;

/**
 * 课程视频controller
 * @author howie
 */
@Controller
@RequestMapping(value = "/video")
public class VideoController extends BaseController{

	private AppLogger logger = new AppLogger(VideoController.class);

	@Resource
	private ITutorshipService tutorshipService;

	@Resource
	private ICourseTutorshipService courseTutorshipService;

	@Resource
	private ICourseVideoService courseVideoService;

	@Resource
	private IExamLibraryService examLibraryService;

	@Resource
	private IVideoService videoService;

	@Value("${requestHost}")
	private String requestHost;

	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/auth/video")
	public ModelAndView tutorship(HttpServletRequest request) {
		logger.entry(ServletUtil.getClientIp(request), "video");
		ApiResult<String> apiResult = new ApiResult<>();
		ModelAndView result = new ModelAndView("/h5/video");
		List<Map<String, Object>> tutorshipList = new ArrayList<>();
		List<Map<String, Object>> videoList = new ArrayList<>();
		String courseId  = ServletUtil.getParameterStr(request, "courseId", "");
		String semesterId  = ServletUtil.getParameterStr(request, "semesterId", "");
		String courseName = ServletUtil.getParameterStr(request, "courseName", "");
		String sort = ServletUtil.getParameterStr(request, "sort", "1");
		String exceedTerm = ServletUtil.getParameterStr(request, "exceedTerm", "0");

		String videoUrl = "";
		String token = sessionUtil.getTokenSession(request);
		Map<String, Object> studentMap = (Map<String, Object>) redisUtil.get(token);
		String studentName = CommonUtils.getStrValueFromMap(studentMap, "studentName", "");
		String headPortrait = CommonUtils.getStrValueFromMap(studentMap, "headPortrait", "");
		String studentType = CommonUtils.getStrValueFromMap(studentMap, "studentType", "");
		String mood = CommonUtils.getStrValueFromMap(studentMap, "mood", "");
		String videoPacketId = ServletUtil.getParameterStr(request, "videoPacketId", "");
		String videoType = "";
		String videoId = "";
		try {
			Map<String, Object> param = new HashMap<>();
			param.put("courseId", courseId);
			//辅导资料
			tutorshipList = courseTutorshipService.findListByMap(param);

			//param.remove("courseId");
			//param.put("videoPacketId", videoPacketId);
			videoList = videoService.findListByMap(param);
//			//课程
//			videoList = courseVideoService.findListByMap(param);
			for(Map<String, Object> map : videoList){
				int videoSort = CommonUtils.getIntegerValueFromMap(map, "sort", 1);
				if(Integer.valueOf(sort) == videoSort){
					videoUrl = CommonUtils.getStrValueFromMap(map, "videoUrl", "");
					videoId = CommonUtils.getStrValueFromMap(map, "id", "");
					if (videoPacketId == ""){
						videoPacketId = CommonUtils.getStrValueFromMap(map, "packetId", "");
					}
					videoType = "1";
					String parentPath = CommonUtils.getStrValueFromMap(map, "parentPath", "");
					String name = CommonUtils.getStrValueFromMap(map, "name", "");
					if(StringUtils.isEmpty(videoUrl)){
						videoType = "2";
						String newVideoUrl = String.format("%s/%s",parentPath, name);
						videoUrl = newVideoUrl.replace("/home", "http://116.255.148.206");
					}else if(videoUrl.contains("116.255.148.206")){
						videoUrl.replace("http://116.255.148.206", String.format("%s/%s", requestHost, "video/router"));
					}
				}
			}

			logger.info(ServletUtil.getClientIp(request));
		} catch (Exception e) {
			dealException(ErrorEnums.SYSTEM_ERROR, e, apiResult, logger);
		}
		result.addObject("tutorshipList", tutorshipList);
		result.addObject("videoList", JSONObject.toJSONString(videoList));
		result.addObject("courseName", courseName);
		result.addObject("courseHeadName", String.format("%s %s 讲",courseName, sort));
		result.addObject("courseId", courseId);
		result.addObject("videoId",videoId);
		result.addObject("videoPacketId",videoPacketId);
		result.addObject("optForSort", sort);
		result.addObject("videoUrl", videoUrl);
		result.addObject("studentName", studentName);
		result.addObject("headPortrait", headPortrait);
		result.addObject("studentType", studentType);
		result.addObject("mood", mood);
		result.addObject("videoType", videoType);
		result.addObject("semesterId",semesterId);
		result.addObject("exceedTerm",exceedTerm);

		return result;
	}

	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/auth/videoPrerecord")
	public ModelAndView videoPrerecord(HttpServletRequest request) {
		logger.entry(ServletUtil.getClientIp(request), "videoPrerecord");
		ApiResult<String> apiResult = new ApiResult<>();
		ModelAndView result = new ModelAndView("/h5/videoPrerecord");
		List<Map<String, Object>> tutorshipList = new ArrayList<>();
		List<Map<String, Object>> videoList = new ArrayList<>();
		String courseId  = ServletUtil.getParameterStr(request, "courseId", "");
		String semesterId  = ServletUtil.getParameterStr(request, "semesterId", "");
		String courseName = ServletUtil.getParameterStr(request, "courseName", "");
		String sort = ServletUtil.getParameterStr(request, "sort", "1");
		String exceedTerm = ServletUtil.getParameterStr(request, "exceedTerm", "0");

		String videoUrl = "";
		String token = sessionUtil.getTokenSession(request);
		Map<String, Object> studentMap = (Map<String, Object>) redisUtil.get(token);
		String studentName = CommonUtils.getStrValueFromMap(studentMap, "studentName", "");
		String headPortrait = CommonUtils.getStrValueFromMap(studentMap, "headPortrait", "");
		String studentType = CommonUtils.getStrValueFromMap(studentMap, "studentType", "");
		String mood = CommonUtils.getStrValueFromMap(studentMap, "mood", "");
		String videoPacketId = ServletUtil.getParameterStr(request, "videoPacketId", "");
		String videoType = "";
		String videoId = "";
		try {
			Map<String, Object> param = new HashMap<>();
			param.put("courseId", courseId);
			//辅导资料
			tutorshipList = courseTutorshipService.findListByMap(param);

			//param.remove("courseId");
			//param.put("videoPacketId", videoPacketId);
			videoList = videoService.findListByMap(param);
//			//课程
//			videoList = courseVideoService.findListByMap(param);
			for(Map<String, Object> map : videoList){
				int videoSort = CommonUtils.getIntegerValueFromMap(map, "sort", 1);
				if(Integer.valueOf(sort) == videoSort){
					videoUrl = CommonUtils.getStrValueFromMap(map, "videoUrl", "");
					videoId = CommonUtils.getStrValueFromMap(map, "id", "");
					if (videoPacketId == ""){
						videoPacketId = CommonUtils.getStrValueFromMap(map, "packetId", "");
					}
					videoType = "1";
					String parentPath = CommonUtils.getStrValueFromMap(map, "parentPath", "");
					String name = CommonUtils.getStrValueFromMap(map, "name", "");
					if("".equals(videoUrl)){
						videoType = "2";
						String newVideoUrl = String.format("%s/%s",parentPath, name);
						videoUrl = newVideoUrl.replace("/home", "http://116.255.148.206");
					}
				}
			}

			logger.info(ServletUtil.getClientIp(request));
		} catch (Exception e) {
			dealException(ErrorEnums.SYSTEM_ERROR, e, apiResult, logger);
		}
		result.addObject("tutorshipList", tutorshipList);
		result.addObject("videoList", JSONObject.toJSONString(videoList));
		result.addObject("courseName", courseName);
		result.addObject("courseHeadName", String.format("%s %s 讲",courseName, sort));
		result.addObject("courseId", courseId);
		result.addObject("videoId",videoId);
		result.addObject("videoPacketId",videoPacketId);
		result.addObject("optForSort", sort);
		result.addObject("videoUrl", videoUrl);
		result.addObject("studentName", studentName);
		result.addObject("headPortrait", headPortrait);
		result.addObject("studentType", studentType);
		result.addObject("mood", mood);
		result.addObject("videoType", videoType);
		result.addObject("semesterId",semesterId);
		result.addObject("exceedTerm",exceedTerm);

		return result;
	}

	/**
	 * 记录观看视频时长
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/auth/video/reckon")
	@ResponseBody
	public ApiResult<String> answer(HttpServletRequest request,
									HttpServletResponse response) {
		logger.entry(ServletUtil.getClientIp(request), "reckon");
		ApiResult<String> result = new ApiResult<>();

		String courseId = ServletUtil.getParameterStr(request, "courseId", "");
		String semesterId = ServletUtil.getParameterStr(request, "semesterId", "");
		String videoId = ServletUtil.getParameterStr(request, "videoId", "");
		String videoPacketId = ServletUtil.getParameterStr(request, "videoPacketId", "");
		String currentTime = ServletUtil.getParameterStr(request, "currentTime", "0");
		String exceedTerm = ServletUtil.getParameterStr(request, "exceedTerm", "0");

		try {
			Map<String, Object> userMap = getStudentMap(request);
			if(userMap == null){
				logger.info("未登陆");
				return result;
			}
			String studentId = CommonUtils.getStrValueFromMap(userMap, "studentId", "");
			//int exits = videoService.videoStudentLimitBtMap(studentId,courseId,semesterId,videoId);

			videoService.videoStudentDelete(studentId,courseId,semesterId);

			int timeMinute =  Integer.parseInt(currentTime) /60;

			videoService.videoStudentSave(serialService.generateSerialNum("", 8),studentId,courseId,semesterId,videoId,timeMinute,Integer.parseInt(currentTime),new Date(),new Date());

			int timeLimit = videoService.videoCourseLimitByMap(courseId,videoPacketId);

			DecimalFormat df = new DecimalFormat("#.00");

			//修改观看时长
			StudentScore studentScore = examLibraryService.findStudentScoreByMap(studentId,courseId,semesterId);

			if (studentScore == null || studentScore.getId().length() < 1){
				StudentScore studentScore1 = new StudentScore();

				studentScore1.setId(serialService.generateSerialNum("", 8));
				studentScore1.setStudentId(studentId);
				studentScore1.setCourseId(courseId);
				studentScore1.setSemesterId(semesterId);

				studentScore1.setVideoTime(timeMinute);
				studentScore1.setRetest(Integer.parseInt(exceedTerm));
				studentScore1.setVideoStatus(1);
				if (timeMinute >= timeLimit || timeLimit == 0)
				{
					studentScore1.setVideoStatus(2);
					studentScore1.setVideoScore(100);
				}else {
					double tempScore = (timeMinute/(double)timeLimit) * 100;
					BigDecimal bg = new BigDecimal(tempScore).setScale(2, RoundingMode.UP);
					studentScore1.setVideoScore(bg.doubleValue());
				}
				examLibraryService.studentScoreSave(studentScore1);
			}else {
				/*if (exits < 1)
				{*/
				studentScore.setVideoTime(timeMinute + studentScore.getVideoTime());
				/*}else{
					if (timeMinute > exits){
						studentScore.setVideoTime(studentScore.getVideoTime() - exits + timeMinute);
					}
				}*/
				if (studentScore.getRetest() != 1) {
					studentScore.setRetest(Integer.parseInt(exceedTerm));
				}
				studentScore.setVideoStatus(1);
				if (studentScore.getVideoTime() >= timeLimit || timeLimit == 0)
				{
					studentScore.setVideoStatus(2);
					studentScore.setVideoScore(100);
				}else {
					double tempScore = (studentScore.getVideoTime() / (double)timeLimit) * 100;
					BigDecimal bg = new BigDecimal(tempScore).setScale(2, RoundingMode.UP);
					studentScore.setVideoScore(bg.doubleValue());
				}

				examLibraryService.studentScoreUpdate(studentScore);
			}

		} catch (Exception e) {
			super.dealException(ErrorEnums.SYSTEM_ERROR, e, result, logger);
			result.setStatus(ErrorEnums.SYSTEM_ERROR.getCode());
			result.setMessage(ErrorEnums.SYSTEM_ERROR.getDesc());
		}

		return result;
	}

	@RequestMapping(value = "/router/**" ,method = {RequestMethod.POST, RequestMethod.GET})
	@ResponseBody
	private String router(HttpServletRequest request, HttpServletResponse response){
		String object = null;
		try {
			String requestURL = request.getRequestURI().trim();
			String fromAddress = requestURL.substring(requestURL.indexOf("router") + 7, requestURL.length());
			String url = String.format("%s/%s", "http://116.255.148.206", fromAddress);

			VnHttpForwardHanlder hanlder = new VnHttpForwardHanlder(response, request, url);
			hanlder.request();
			Map map = hanlder.getReturnData();
			if(map != null) {
				object = new String((byte[])((byte[])map.get("MESSAGE")), "UTF-8");
				logger.doInfo("返回信息长度", object==null ? 0 :object.length());
			}
		} catch (Exception e) {
			logger.doInfo("请求异常", e.getMessage());
			object =  "{\"error\": \"响应结果为空\"}";
		}
		return object;
	}
}
